<script setup>
import { ref, watch, watchEffect } from 'vue'

const question = ref('')
const answer = ref('Questions usually contains a question mark...')
const loading = ref(false)

watch(question, async (newQuestion, oldQuestion) => {
    console.log(oldQuestion)
    if (newQuestion.includes('?')) {
        loading.value = true
        answer.value = 'Thinking...'
        try {
            const res = await fetch('https://yesno.wtf/api')
            answer.value = (await res.json()).answer
        } catch (e) {
            answer.value = 'Error! Could not reach the API.' + e
        } finally {
            loading.value = false
        }
    }
})

const x = ref(0)
const y = ref(0)
const sum = ref('')
const xy = ref('')
watch(
    () => x.value + y.value,
    (newSum, oldSum) => {
        sum.value = `New sum of x + y is ${newSum}. Old sum of x + y is ${oldSum}.`
    }
)
watch([x, () => y.value], ([newX, newY], [oldX, oldY]) => {
    xy.value = `New x is ${newX} and y is ${newY}. Old x is ${oldX} and y is ${oldY}`
})

const API = `https://api.github.com/repos/vuejs/core/commits?per_page=3&sha=`
const branches = ['main', 'v2-compat']
const currentBranch = ref(branches[0])
const commits = ref(null)

watchEffect(async () => {
    const url = `${API}${currentBranch.value}`
    commits.value = await (await fetch(url)).json()
})
</script>

<template>
    <h1>demo 1</h1>
    <p>Ask a question:
        <input v-model="question" :disabled="loading">
    </p>
    <p>{{ answer }}</p>

    <h1>demo 2</h1>
    <p>x: <input type="number" v-model="x"></p>
    <p>y: <input type="number" v-model="y"></p>
    <p>{{ sum }}</p>
    <p>{{ xy }}</p>

    <h1>GitHub commit</h1>
    <template v-for="b in branches" :key="b">
        <input type="radio" v-model="currentBranch" :id="b" :value="b" style="margin-right: 5px;">
        <label :for="b" style="margin-right: 15px;">{{ b }}</label>
    </template>

    <p>vuejs/vue@{{ currentBranch }}</p>
    <ul>
        <li v-for="{ html_url, sha, author, commit } in commits" :key="sha">
            <a :href="html_url" target="_blank">{{ sha }}</a>
            -
            <span>{{ commit.message }}</span>
            <br />
            by <a :href="author.html_url" target="_blank">{{ commit.author.name }}</a>
            at
            <span>{{ commit.author.date }}</span>
        </li>
    </ul>
</template>